package TCPMain;

import static TCPMain.Constant.ACTION_PublishTask;
import static TCPMain.Constant.ACTION_SendFolder;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.widget.Toast;

import com.example.tcp2504.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import TCPMain.utils.DataUtil;

public class ShowDataActivity extends AppCompatActivity implements View.OnClickListener {
    private Button uploadButton;
    private Button remoteFilesButton;
    private Button transferListButton;
    private Button logoutButton;
    private RecyclerView recyclerView;
    private FloderService floderService;
    private FileService fileService;
    private static final String TAG = "ShowDataActivity";
    private boolean isBound = false;
    private Intent intent;
    private DataUtil dataUtil = new DataUtil();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_data);
        // 初始化UI元素
        uploadButton = findViewById(R.id.upload_button);//上传按钮
        remoteFilesButton = findViewById(R.id.remote_files_button);//远程文件按钮
        transferListButton = findViewById(R.id.transfer_list_button);//传输列表按钮
        logoutButton = findViewById(R.id.logout_button);//登出按钮
        uploadButton.setOnClickListener(this);
        remoteFilesButton.setOnClickListener(this);
        transferListButton.setOnClickListener(this);
        logoutButton.setOnClickListener(this);

        TCPShowDataAdapter adapter = new TCPShowDataAdapter();
        recyclerView = findViewById(R.id.file_list);//文件列表
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this::onItemClick);//设置项目的点击事件

        // 获取传递过来的 Intent
        Intent LoginIntent = getIntent();
        String ServerData = LoginIntent.getStringExtra("server");
        Log.d(TAG, "Received Intent: " + ServerData);
        String[] parts = ServerData.split(":");

        // 绑定到 Service
        Intent FloderServiceIntent = new Intent(this, FloderService.class);
        bindService(FloderServiceIntent, FloderserviceConnection, Context.BIND_AUTO_CREATE);
        intent = new Intent(this, FloderService.class);
        startService(intent);

        Intent  FileServiceIntent = new Intent(this, FileService.class);
        bindService(FileServiceIntent, FileserviceConnection, Context.BIND_AUTO_CREATE);
        intent = new Intent(this, FileService.class);
        startService(intent);

        intent=new Intent(ACTION_PublishTask);
        // 注册广播接收器
        LocalBroadcastManager.getInstance(this).registerReceiver(
                tcpFloderReceiver,
                new IntentFilter(ACTION_SendFolder)
        );

    }

    private ServiceConnection FloderserviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            FloderService.MyBinder binder = (FloderService.MyBinder) service;
            floderService = binder.getService();
            Log.d(TAG, "Service connected");
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
            Log.d(TAG, "Service disconnected");
        }
    };
    private ServiceConnection FileserviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            FileService.MyBinder binder = (FileService.MyBinder) service;
            fileService = binder.getService();
            Log.d(TAG, "Service connected");
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
            Log.d(TAG, "Service disconnected");
        }
    };
    /**
     * 创建一个内部类继承 BroadcastReceiver，用于接收广播,它将处理接收到的广播消息。
     */
    private BroadcastReceiver tcpFloderReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("FolderData");
            if (message == null) {
                Log.d(TAG, "Received empty message");
            } else {
                Log.d(TAG, "Received message: " + message);
                /**
                 * 确保 UI 更新在主线程上执行
                 */
                TCPShowDataAdapter adapter = new TCPShowDataAdapter();
                runOnUiThread(() -> {
                    recyclerView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                });
            }
        }
    };

    /**
     * 创建表单点击事件的响应函数
     */
    private void onItemClick(int position) {
        boolean Floder = false;//当前选择是否位文件夹
        // 处理表单点击事件
        Log.d(TAG, AllData.getAllJsonData().toString());
        Log.d(TAG, AllData.getAllNames().toString());

        //获取文件/文件夹的名字
        String fileOrFloderName = AllData.getAllNames().get(position);
        Log.d(TAG, "点击项目：" + fileOrFloderName + " 长度：" + position);
        Toast.makeText(this, "开始下载：" + fileOrFloderName, Toast.LENGTH_SHORT).show();
        JSONObject outData = new JSONObject();

        //判断当前选择的项目是否为文件夹
        if (AllData.getFloderNames().contains(fileOrFloderName)) {
            Floder = true;
        }


        if (!Floder) {//文件，如果从全部数据中查找到的是文件，那么调用Client的SendFile方法
            try {
                //初始化文件名字列表和文件长度列表
                Log.d(TAG, "文件");
                List<Long> DownLengths = new ArrayList<>();//要下载的文件的长度列表
                List<String> DownNames = new ArrayList<>();//要下载的文件的名字列表
                Long FileLength = AllData.getFileDatas().get(fileOrFloderName);//获取选中的item的文件长度
                DownNames.add(fileOrFloderName);//加入获取选中的item的名字
                DownLengths.add(FileLength);//加入获取选中的item的文件长度
                outData.put("Command", "SendFile");
                outData.put("SendFileNames", DownNames);
                outData.put("SendFileLengths", DownLengths);
                outData.put("IP", AllData.getSERVER_IP());
                outData.put("Port", AllData.getSERVER_PORT());
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }


        } else {//如果从全部数据中查找到的是文件夹，那么调用Client的SendFolder方法
            Log.d(TAG, "文件夹");
            try {
                outData.put("Command", "SendFolder");
                outData.put("SendFolder", fileOrFloderName);
                outData.put("IP", AllData.getSERVER_IP());
                outData.put("Port", AllData.getSERVER_PORT());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 发送广播通知 service
        Intent broadcastIntent = new Intent(ACTION_PublishTask);
        broadcastIntent.putExtra("Task", outData.toString());
        sendBroadcast(broadcastIntent);

    }

    /**
     * 全部按钮
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        Log.d(TAG, "onClick: " + id);
        if (id == R.id.upload_button) {
            //上传按钮点击事件
            //TODO
        } else if (id == R.id.remote_files_button) {
            //远程文件按钮点击事件
            //TODO
            //还要判断是否已经有数据了，不然会一直跳转到主文件夹
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("Command", "SendFolder");
                jsonObject.put("SendFolder", "");
                jsonObject.put("IP", AllData.getSERVER_IP());
                jsonObject.put("Port", AllData.getSERVER_PORT());
            } catch (Exception e) {
                e.printStackTrace();
            }
            intent.putExtra("Task", jsonObject.toString());
            sendBroadcast(intent);
        } else if (id == R.id.transfer_list_button) {
            //传输列表按钮点击事件
            //TODO
            Intent intent1 = new Intent(ShowDataActivity.this, DownActivity.class);
            intent1.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent1);
            onPause();
        } else if (id == R.id.logout_button) {
            //登出按钮点击事件
            //TODO
            Intent intent1 = new Intent(ShowDataActivity.this, loginActivity.class);
            intent1.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent1);
            onDestroy();
        } else {
            //其他按钮点击事件
            //TODO
        }
    }

    /**
     *
     */
    @Override
    protected void onPostResume() {
        super.onPostResume();
        //Toast.makeText(this, TAG+":onPostResume", Toast.LENGTH_SHORT).show();
    }

    /**
     *
     */
    @Override
    protected void onStart() {
        super.onStart();
//        Toast.makeText(this, TAG+":onStart", Toast.LENGTH_SHORT).show();
    }

    /**
     *
     */
    @Override
    protected void onStop() {
        super.onStop();
//        Toast.makeText(this, TAG+":onStop", Toast.LENGTH_SHORT).show();
    }

    /**
     *
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Toast.makeText(this, TAG+":onDestroy", Toast.LENGTH_SHORT).show();
    }

    /**
     *
     */
    @Override
    protected void onPause() {
        super.onPause();
//        Toast.makeText(this, TAG+":onPause", Toast.LENGTH_SHORT).show();
    }

    /**
     *
     */
    @Override
    protected void onResume() {
        super.onResume();
//        Toast.makeText(this, TAG+":onResume", Toast.LENGTH_SHORT).show();
    }
}


